package com.jwm.power.service.impl;

import cn.dev33.satoken.stp.StpUtil;

import com.jwm.power.model.common.EnumOperate;
import com.jwm.power.model.common.EnumResult;
import com.jwm.power.model.entity.InquiryT;
import com.jwm.power.model.entity.Logs;
import com.jwm.power.model.entity.Users;
import com.jwm.power.model.reponse.ResponseData;
import com.jwm.power.repository.InquiryRepository;
import com.jwm.power.repository.LogisticsRepository;
import com.jwm.power.repository.LogsRepository;
import com.jwm.power.repository.T6FreightRepository;
import com.jwm.power.service.InquiryService;
import com.jwm.power.util.Ut;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.ServletRequestDataBinder;
import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.util.Objects;
import java.util.Optional;

@Service
@Transactional
public class InquiryServiceImpl implements InquiryService {

    @Autowired
    private InquiryRepository inquiryRepository;
    @Autowired
    private LogsRepository logsRepository;

    @Override
    public ResponseData SaveInquiry(HttpServletRequest request){
        try {
            Users users = (Users) StpUtil.getSession().get("users");
            System.out.println(users.getIsSale() + "," + users.getName());
            InquiryT model_New = new InquiryT();
            ServletRequestDataBinder binder =
                    new ServletRequestDataBinder(model_New);
            binder.bind(request);
            Integer operationType = 0;
            if(Optional.ofNullable(model_New.getId()).isPresent()){
                operationType = 1;
                InquiryT inquiryT = inquiryRepository.findByid(model_New.getId());
                if (!inquiryT.getSales().equals(model_New.getSales())) {
                    return new ResponseData(EnumResult.WORK_FAIL_TNAME, model_New);
                }
            }
            model_New.setFormstatus(-1);
            String t6price = request.getParameter("t6price");
            if(Objects.equals(t6price, "")){
                model_New.setT6price(BigDecimal.valueOf(0));
            }
            String inquirydate = request.getParameter("inquirydate");
            model_New.setInquirydate(Ut.formatStrToDate(inquirydate, "yyyy-MM-dd"));
            inquiryRepository.save(model_New);
            // 日志
            Logs log = Ut.SaveLog("inquiry", model_New.getSales(), operationType == 1 ? EnumOperate.EDIT : EnumOperate.ADD, users);
            logsRepository.save(log);
            return new ResponseData(EnumResult.SUCCESS, null);
        }catch (Exception e){
            e.printStackTrace();
            return new ResponseData(EnumResult.Exception.getCode(), e.getMessage(), null);
        }
    }
}
